package com.lymei.core.config.security;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.lymei.common.utils.RedisUtils;
import com.lymei.core.modules.system.service.IOnlineService;
import com.lymei.lib.po.system.UserDetailsImpl;
import com.lymei.lib.properties.AppProperties;
import com.lymei.lib.vo.system.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedHashSet;

/**
 * @author lymei
 * @title: TokenFilter
 * @projectName scui-admin
 * @description: TODO
 * @date 2022/1/2011:33
 */
@Component
public class TokenFilter extends OncePerRequestFilter {

    @Autowired
    private AppProperties appProperties;

    @Autowired
   private IOnlineService onlineService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        UserVo loginUser = onlineService.get(request);
        //如果loginUser 不是null 说明已鉴权 需要对数据进行鉴权
        if (loginUser != null){
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(new UserDetailsImpl(loginUser), null,new LinkedHashSet<>());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        filterChain.doFilter(request,response);
    }


    public UserVo get(HttpServletRequest request){
        String token = request.getHeader(appProperties.getOnline().getTokenHeaderName());
        String prefix = appProperties.getOnline().getTokenPrefix();
        if (StringUtils.isBlank(token)){
            return null;
        }
        if (!token.contains(prefix)){
            return null;
        }
        token = token.replace(prefix,"");
        if (onlineService.has(token)){
            return onlineService.get(token);
        }
        return null;
    }

}
